package com.wwj.admin.params.controller;

import com.github.pagehelper.Page;
import com.wwj.core.system.entity.Parameter;
import com.wwj.core.system.service.IParameterService;
import com.wwj.framework.controller.BaseController;
import com.wwj.framework.utils.Page2EasyUiData;
import com.wwj.framework.utils.ReturnData;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("params")
public class ParamsController extends BaseController {
    private final String INDEX = "/admin/params/params";

    @Resource
    private IParameterService parameterService;

    @RequestMapping(value={"","/","/index","/list"})
    public String index(){
        return INDEX;
    }

    @RequestMapping("/listData.json")
    @ResponseBody
    public ReturnData list(String search, int offset, int limit)throws Exception{
        Map<String,Object> params = new HashMap<String,Object>();
        if(null != search && !"".equals(search)) {
            search = new String(search.getBytes("ISO8859-1"), "UTF-8");
            params.put("search",search);
        }
        Page<Parameter> records = parameterService.findByPage(offset, limit, params);
        return new ReturnData().success(Page2EasyUiData.format(records));
    }

    @RequestMapping("/param/add")
    @ResponseBody
    public ReturnData add(Parameter parameter)throws Exception{
        parameterService.addParameter(parameter);
        return new ReturnData().success("ok");
    }

    @RequestMapping("/param/update")
    @ResponseBody
    public ReturnData update(Parameter parameter) throws Exception {
        parameterService.modifyParameter(parameter);
        return new ReturnData().success("ok");
    }

    @RequestMapping("/param/{id}")
    @ResponseBody
    public ReturnData findById(@PathVariable("id")int id){
        try {
            Parameter parameter = parameterService.findById(id);
            return new ReturnData().success(parameter);
        } catch (Exception e) {
            e.printStackTrace();
            return new ReturnData().failure("error");
        }
    }

    @RequestMapping(value = "/param/delete")
    @ResponseBody
    public ReturnData delete(int id){
        try {
            parameterService.deleteById(id);
            return new ReturnData().success("ok");
        } catch (Exception e) {
            e.printStackTrace();
            return new ReturnData().failure("error");
        }
    }
}
